package com.houkunlin.knife4j;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

/**
 * @author HouKunLin
 */
@Component
@AllArgsConstructor
public class Knife4jCommandLineRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(Knife4jCommandLineRunner.class);
    private final ConfigurableEnvironment environment;
    private final String[] hosts = new String[]{"127.0.0.1", "localhost", "devlan.host"};

    @Override
    public void run(final String... args) throws Exception {
        String port = environment.getProperty("server.port");
        String contextPath = environment.getProperty("server.servlet.context-path");
        if (contextPath != null && !contextPath.startsWith("/")) {
            contextPath = String.format("%s%s", "/", contextPath);
        }
        if (contextPath != null && contextPath.endsWith("/")) {
            contextPath = contextPath.substring(0, contextPath.length() - 1);
        }
        if (contextPath == null) {
            contextPath = "";
        }
        for (final String host : hosts) {
            logger.info("Swagger 文档部署访问路径 http://{}:{}{}/doc.html", host, port, contextPath);
        }
    }
}
